package com.example.administrator.school;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.dmcbig.mediapicker.PickerActivity;
import com.dmcbig.mediapicker.PickerConfig;
import com.dmcbig.mediapicker.entity.Media;
import com.example.administrator.school.adapter.FileAdapter;
import com.example.administrator.school.bean.MediaBean;
import com.example.administrator.school.db.MediaHelper;
import com.xiumiing.uilibrary.base.BaseActivity;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
//import droidninja.filepicker.FilePickerConst;

public class UpDataActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.spinner)
    Spinner mSpinner;
    @BindView(R.id.search_bar)
    SearchView mSearchBar;
    @BindView(R.id.rv_vedio)
    RecyclerView mRvVedio;
    @BindView(R.id.SwipeRefresh)
    SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.number_progress_bar)
    NumberProgressBar mNumberProgressBar;
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.tv_right)
    TextView mTvRight;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;
    private RecyclerView recyclerView;
    private ArrayList<MediaBean> mData;
    private FileAdapter mAdapter;
    ArrayList<Media> mSelect;
    int mPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_updata);
        ButterKnife.bind(this);

        setToolbarRightText("添加上传");
        mSwipeRefresh.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        mSwipeRefresh.setOnRefreshListener(this);
        mSwipeRefresh.setEnabled(false);
        ArrayList<String> list = new ArrayList<>();

        list.add("视频");
        list.add("图片");
        list.add("文档");
//        list.add("语音");

        /*
         * 第二个参数是显示的布局
         * 第三个参数是在布局显示的位置id
         * 第四个参数是将要显示的数据
         */
        ArrayAdapter adapter2 = new ArrayAdapter<>(this, R.layout.item, R.id.textview, list);
        mSpinner.setAdapter(adapter2);
        mSpinner.setOnItemSelectedListener(new spinner2Listener());
        mRvVedio.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new FileAdapter(mData);
        mRvVedio.setAdapter(mAdapter);

        mAdapter.setOnLoadMoreListener(this, mRvVedio);
    }

    @OnClick(R.id.tv_right)
    public void onViewClicked() {
        if (fileType == 2) {
            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.WRITE_EXTERNAL_STORAGE)
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> permissions) {
                            LogUtils.d("onGranted");
                            FilePickerBuilder.getInstance().setMaxCount(10)
                                    .setActivityTheme(R.style.LibAppTheme)
                                    .pickFile(UpDataActivity.this);
                        }
                    })
                    // Storage permission are not allowed.
                    .onDenied(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {
                            LogUtils.d("onDenied");
                        }
                    })
                    .start();
            return;
        }

        Intent intent = new Intent(UpDataActivity.this, PickerActivity.class);
        intent.putExtra(PickerConfig.SELECT_MODE, fileType == 0 ? PickerConfig.PICKER_VIDEO : PickerConfig.PICKER_IMAGE);//default image and video (Optional)
        long maxSize = 188743680L;//long long long long类型
        intent.putExtra(PickerConfig.MAX_SELECT_SIZE, maxSize); //default 180MB (Optional)
        intent.putExtra(PickerConfig.MAX_SELECT_COUNT, 15);  //default 40 (Optional)
//        intent.putExtra(PickerConfig.DEFAULT_SELECTED_LIST, mSelect); //(Optional)默认选中的照片
        UpDataActivity.this.startActivityForResult(intent, 200);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FilePickerConst.REQUEST_CODE_PHOTO:
                if (resultCode == Activity.RESULT_OK && data != null)
//                {
//                    photoPaths = new ArrayList<>();
//                    photoPaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
//                }
                    break;
            case FilePickerConst.REQUEST_CODE_DOC:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    final List<String> docPaths = new ArrayList<>();
                    docPaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS));
                    if (docPaths.size() == 0) {
                        return;
                    }
                    mNumberProgressBar.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < 100; i++) {
                                try {
                                    Thread.sleep(50);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                final int finalI = i;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mNumberProgressBar.setProgress(finalI);
                                    }
                                });
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mData = new ArrayList<>();
                                    for (String docPath : docPaths) {
                                        MediaBean mediaBean = MediaBean.toMediaBean(docPath);
                                        mData.add(mediaBean);
                                        MediaHelper.getInstance().insertData(mediaBean);
                                    }
                                    mAdapter.setNewData(mData);
                                    mAdapter.loadMoreEnd();
                                    mNumberProgressBar.setProgress(100);
                                    App.getInstance().showToast("上传成功");

                                }
                            });

                        }
                    }).start();

                }
                break;
        }
        if (requestCode == 200 && resultCode == PickerConfig.RESULT_CODE) {
            mSelect = data.getParcelableArrayListExtra(PickerConfig.EXTRA_RESULT);
            if (mSelect == null || mSelect.size() == 0) {
                return;
            }
            mNumberProgressBar.setVisibility(View.VISIBLE);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        final int finalI = i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mNumberProgressBar.setProgress(finalI);
                            }
                        });
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("mSelect", "mSelect.size" + mSelect.size());
                            mData = new ArrayList<>();
                            for (Media media : mSelect) {
                                Log.i("media", media.path);
                                Log.e("media", "s:" + media.size);
                                media.mediaType = fileType;
                                MediaBean mediaBean = MediaBean.toMediaBean(media);
                                mData.add(mediaBean);
                                MediaHelper.getInstance().insertData(mediaBean);
                            }
                            mAdapter.setNewData(mData);
                            mAdapter.loadMoreEnd();
                            mNumberProgressBar.setProgress(100);
                            App.getInstance().showToast("上传成功");

                        }
                    });

                }
            }).start();


        }
    }

    private void loadData() {
//        mSelect.add()
    }


    @Override
    public void onRefresh() {
        mPage = 0;
        loadData();
    }

    @Override
    public void onLoadMoreRequested() {
        mPage++;
        loadData();
    }

    int fileType;

    class spinner2Listener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0) {
                fileType = 0;
            } else if (position == 1) {
                fileType = 1;
            } else if (position == 2) {
                fileType = 2;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            System.out.println("nothingSelect");
        }
    }
}
